import React, { useEffect, useState } from 'react'
import { useHistory } from 'react-router-dom'
import { Row, Col } from 'antd'
import { getProducts } from '@/api/product'
import { showLoading, hideLoading } from '@/register/globalFun'
import ProductItem from '@/components/ProductItem'
import { typeProduct } from '@/types/product'
import './index.scss'

const Home = () => {
  const history = useHistory()
  const [products, setProducts] = useState<typeProduct[]>([])

  useEffect(() => {
    loadProducts()
  }, [])

  const loadProducts = async() => {
    showLoading()
    try {
      const res = await getProducts({
        pageNum: 1,
        pageSize: 100
      })

      setProducts(res.data.products)
    } catch (err) {
      console.log(err)
    }
    hideLoading()
  }

  return products
    ? (
      <div className="home">
        <h1>最新产品</h1>
        <Row gutter={[20, 20]}>
          {products.map((product:typeProduct) => (
            <Col
              className="product"
              key={product._id}
              onClick={() => { history.push(`/product/${ product._id }`) }}
              span={6}
            >
              <ProductItem product={product} />
            </Col>
          ))}
        </Row>
      </div>
    )
    : null
}

export default Home
